package com.yuanhua.sim.client;

import com.yuanhua.core.base.entity.LoginReqBean;
import com.yuanhua.core.base.entity.MsgReqBean;
import com.yuanhua.sim.client.decoder.MyDecoder;
import com.yuanhua.sim.client.decoder.MyEncoder;
import com.yuanhua.sim.client.socket.SuperImChannelInitializer;
import com.yuanhua.sim.client.utils.FlagUtils;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.util.Scanner;
import java.util.concurrent.locks.LockSupport;

/**
 * 测试消息通信
 * 客户端启动之后调用网关获取服务端地址，连接服务端
 * @return:
 * @author songguoxiang
 * @date: 2022/8/11 15:45
 */
@Slf4j
public class ChatClient {

    public static void main(String[] args) throws Exception {
        String host = "10.8.0.8";

        Long userId = Long.valueOf(args[0]);
        String userName = args[1];
        Long toUserId = Long.valueOf(args[2]);

        //请求网关、获取netty 服务器

        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(512*1024, 1024*1024))
                    .channel(NioSocketChannel.class)
                    .handler(new SuperImChannelInitializer());
            ChannelFuture channelFuture = bootstrap.connect(host, 8887).sync();
            //得到 channel
            Channel channel = channelFuture.channel();
            System.out.println("========" + channel.localAddress() + "========");
            //先登录注册自己

            channel.writeAndFlush(LoginReqBean.builder().userid(userId).username(userName).build());
            //客户端需要输入信息， 创建一个扫描器
            //功能列表
            //查询在线用户
            //选择在线用户
            //发送消息

            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine() && FlagUtils.shouldContinueReadingInput) {
                String msg = scanner.nextLine();
                MsgReqBean msgReqBean = new MsgReqBean();
                msgReqBean.setMsg(msg);
                msgReqBean.setTag(1);
                msgReqBean.setFromuserid(userId);
                msgReqBean.setTouserid(toUserId);
                //通过 channel 发送到服务器端
                channel.writeAndFlush(msgReqBean);
            }
            //对关闭通道进行监听
            channelFuture.channel().closeFuture().sync();
            System.out.println("服务端断开连接，客户端下线");
        } finally {
            group.shutdownGracefully();
        }
    }
}